package lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by wangyg 
 * on 2017/3/27 11:34
 */
public class CacheDemo {

	private Map<String, Object> cache = new HashMap<String, Object>();

	private ReadWriteLock rwl = new ReentrantReadWriteLock();

	public Object getData(String key) {
		//1、先开个读锁
		rwl.readLock().lock();
		Object value = null;
		try {
			value = cache.get(key);
			if (value == null) {
				//2、缓存数据为空，读解锁，开写锁
				rwl.readLock().unlock();
				rwl.writeLock().lock();
				try {
					//3、再次判空，防止2出存在多个线程，一个写完以后，下一个再写（不需要再写）
					if (value == null) {
						value = "aaaa";	// 实际是去数据库拿数据
					}
				} finally {
					rwl.writeLock().unlock();
				}
				//4、上读锁，是为了和最后finally处对应，恢复锁的完整
				rwl.readLock().lock();
			}
		} finally {
			rwl.readLock().unlock();
		}
		return value;
	}
}

